package com.hokook.service.impl;

import com.hokook.delayed.DelayedPlainTask;
import com.hokook.entity.PlainTask;
import com.hokook.service.ITaskService;
import com.hokook.task.PlainTaskRunable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class TaskServiceImpl implements ITaskService {

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    List<PlainTask> plainTaskList = new ArrayList<>();

    /**
     * 初始化数据
     */
    @PostConstruct
    public void init() {
        initData();
        for (int i = 0; i < 8; i++) {
            DelayQueue delayQueue = new DelayQueue();
            plainTaskList.stream().forEach(x -> {
                delayQueue.add(new DelayedPlainTask(x, x.getId(), x.getInterval()));
            });
            PlainTaskRunable plainTaskRunable = new PlainTaskRunable(delayQueue);
            executorService.execute(plainTaskRunable);
        }
    }

    public void initData() {
        for (int j = 1; j < 11; j++) {
            PlainTask plainTask = new PlainTask();
            plainTask.setCreateTime(new Date());
            plainTask.setId(Long.parseLong((j + 1) + ""));
            plainTask.setInterval(j * 5000L);
            plainTask.setStatus(0);
            plainTask.setPid(1L);
            plainTask.setTaskName("任务: #"+j);
            plainTaskList.add(plainTask);
        }
    }


}
